package br.jcrsistemas.database;

import java.sql.Connection;
import java.sql.SQLException;

import org.postgresql.ds.PGPoolingDataSource;

import br.jcrsistemas.util.Configuracoes;
import br.jcrsistemas.util.Util;

public class ConexaoPostgres implements Conexao {
	private static Connection conexao = null;
	private static PGPoolingDataSource source = new PGPoolingDataSource();
	static {
		source.setDataSourceName("PGSQLPOOL");
		source.setServerName(Configuracoes.getHost());
		source.setDatabaseName(Configuracoes.getDbName());
		source.setUser(Configuracoes.getUsuarioBanco());
		source.setPassword(Configuracoes.getSenhaBanco());
		source.setMaxConnections(Configuracoes.getMaxConnection());
	}

	@Override
	public String getLastInsertID(String tabela, String campo) {
		return "SELECT CURRVAL(pg_get_serial_sequence('" + tabela + "','"
				+ campo + "'))";
	}

	@Override
	public Connection getConnection() throws SQLException {
		if (conexao == null) {
			conexao = source.getConnection();
		}
		return conexao;
	}

	@Override
	public String getDialeto() {
		return "org.hibernate.dialect.PostgreSQLDialect";
	}

	@Override
	public String getURLConexao() {
		return "jdbc:postgresql://" + Configuracoes.getHost() + ":"
				+ Configuracoes.getPorta() + "/" + Configuracoes.getDbName();
	}

	@Override
	public String getDriverClass() {
		return "org.postgresql.Driver";
	}

	@Override
	public void iniciaTransacao() throws SQLException {
		if (conexao == null) {
			conexao = source.getConnection();
		}
		conexao.setAutoCommit(false);
	}

	@Override
	public void encerraTransacao() throws SQLException {
		if (conexao == null) {
			conexao = source.getConnection();
		}
		conexao.setAutoCommit(true);

	}

	@Override
	public void commit() throws SQLException {
		if (conexao == null) {
			conexao = source.getConnection();
		}
		conexao.commit();
	}

	@Override
	public void rollback() {
		try {
			if (conexao == null) {
				conexao = source.getConnection();
				conexao.rollback();
			}
		} catch (SQLException e) {
			Util.loga("ROLLBACK\n" + e);
			Util.trataErro(e);
			e.printStackTrace();
		}
	}

}
